package net.sk.china.platform.service.impl.system;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import net.sk.china.platform.dao.system.SystemFormTempDao;
import net.sk.china.platform.model.system.SystemFormTemp;
import net.sk.china.platform.request.system.SystemFormCheckRequest;
import net.sk.china.common.request.SystemFormItemCheckRequest;
import net.sk.china.platform.request.system.SystemFormTempRequest;
import net.sk.china.platform.request.system.SystemFormTempSearchRequest;
import net.sk.china.platform.response.system.SystemConfigFormItemConfigRegListResponse;
import net.sk.china.platform.response.system.SystemConfigFormItemResponse;
import net.sk.china.platform.response.system.SystemConfigFormResponse;
import net.sk.china.platform.service.system.SystemFormTempService;
import net.sk.china.platform.utils.ValidateFormUtil;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.request.PageParamRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/6/3 10:39
 * // +----------------------------------------------------------------------
 */

@Service
public class SystemFormTempServiceImpl extends ServiceImpl<SystemFormTempDao, SystemFormTemp> implements SystemFormTempService {

    @Resource
    private SystemFormTempDao dao;

    /**
     * 列表
     * @param request 请求参数
     * @param pageParamRequest 分页类参数
     * @return {@code List<SystemFormTemp>}
     */
    @Override
    public List<SystemFormTemp> getList(SystemFormTempSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 SystemFormTemp 类的多条件查询
        LambdaQueryWrapper<SystemFormTemp> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.eq(SystemFormTemp::getId, request.getKeywords()).
                    or().like(SystemFormTemp::getName, request.getKeywords()).
                    or().like(SystemFormTemp::getInfo, request.getKeywords());
        }
        lambdaQueryWrapper.orderByDesc(SystemFormTemp::getId);
        return dao.selectList(lambdaQueryWrapper);
    }

    /**
     * 验证item规则
     * @param systemFormCheckRequest SystemFormCheckRequest 表单数据提交
     */
    @Override
    public void checkForm(SystemFormCheckRequest systemFormCheckRequest) {
        // 循环取出item数据， 组合成 key => val 的map格式
        HashMap<String, String> map = new HashMap<>(16);
        for (SystemFormItemCheckRequest systemFormItemCheckRequest : systemFormCheckRequest.getFields()) {
            map.put(systemFormItemCheckRequest.getName(), systemFormItemCheckRequest.getValue());
        }

        //取出表单模型的数据
        SystemFormTemp formTemp = getById(systemFormCheckRequest.getId());

        //解析表单规则进行验证
        SystemConfigFormResponse systemConfigFormResponse;
        try {
            systemConfigFormResponse =  JSONObject.parseObject(formTemp.getContent(), SystemConfigFormResponse.class);
        } catch (Exception e) {
            throw new TalkException("模板表单 【" + formTemp.getName() + "】 的内容不是正确的JSON格式！");
        }

        SystemConfigFormItemResponse systemConfigFormItemResponse;
        for (String item : systemConfigFormResponse.getFields()) {
            systemConfigFormItemResponse = JSONObject.parseObject(item, SystemConfigFormItemResponse.class);
            // 字段 name
            String model = systemConfigFormItemResponse.get__vModel__();

            if(systemConfigFormItemResponse.get__config__().getRequired() && map.get(model).equals("")) {
                throw new TalkException(systemConfigFormItemResponse.get__config__().getLabel() + "不能为空！");
            }
            //正则验证
            checkRule(systemConfigFormItemResponse.get__config__().getRegList(), map.get(model),  systemConfigFormItemResponse.get__config__().getLabel());
        }
    }


    /**
     * 新增表单模板
     * @param systemFormTempRequest 新增参数
     * @return {@code boolean}
     */
    @Override
    public boolean add(SystemFormTempRequest systemFormTempRequest) {
        try {
            JSONObject.parseObject(systemFormTempRequest.getContent(), SystemConfigFormResponse.class);
        } catch (Exception e) {
            throw new TalkException("模板表单 【" + systemFormTempRequest.getName() + "】 的内容不是正确的JSON格式！");
        }

        SystemFormTemp systemFormTemp = new SystemFormTemp();
        BeanUtils.copyProperties(systemFormTempRequest, systemFormTemp);
        return save(systemFormTemp);
    }

    /**
     * 修改表单模板
     * @param id integer id
     * @param systemFormTempRequest 修改参数
     * @return {@code boolean}
     */
    @Override
    public boolean edit(Integer id, SystemFormTempRequest systemFormTempRequest) {
        try {
            JSONObject.parseObject(systemFormTempRequest.getContent(), SystemConfigFormResponse.class);
        } catch (Exception e) {
            throw new TalkException("模板表单 【" + systemFormTempRequest.getName() + "】 的内容不是正确的JSON格式！");
        }

        SystemFormTemp systemFormTemp = new SystemFormTemp();
        BeanUtils.copyProperties(systemFormTempRequest, systemFormTemp);
        systemFormTemp.setId(id);
        return updateById(systemFormTemp);
    }

    /**
     * 验证item规则
     * @param regList List<SystemConfigFormItemConfigRegListVo 正则表达式列表
     * @param value String 验证的值
     * @param name String 提示语字段名称
     */
    private void checkRule(List<SystemConfigFormItemConfigRegListResponse> regList, String value, String name) {
        if(regList.size() > 0) {
            for (SystemConfigFormItemConfigRegListResponse systemConfigFormItemConfigRegListVo : regList) {
                if(!ValidateFormUtil.regular(value, name, systemConfigFormItemConfigRegListVo.getPattern())) {
                    throw new TalkException(systemConfigFormItemConfigRegListVo.getMessage());
                }
            }
        }
    }
}

